import { ref } from 'vue';

// 从URL参数获取配置
const getApiParams = () => {
  const urlParams = new URLSearchParams(window.location.search);
  
  // 尝试从URL参数获取id和apikey
  const id = urlParams.get('id')
  const apiKey = urlParams.get('apikey') || import.meta.env.VITE_apikey; // 默认使用环境变量
  
  // 构建base_url
  const baseApiUrl = `https://ai.htecus.com/api/application/${id}/chat/completions`;
  
  return {
    baseUrl: baseApiUrl,
    apiKey: apiKey
  };
};

// 获取API参数
const { baseUrl: BASE_URL, apiKey: API_KEY } = getApiParams();
const MODEL = import.meta.env.VITE_model;

// 提取API路径的最后部分，用于代理
const getProxyUrl = () => {
  try {
    const url = new URL(BASE_URL);
    // 将URL的路径部分添加到本地代理前缀
    return `/api${url.pathname}`;
  } catch (e) {
    console.error('解析URL时出错:', e);
    return '/api/chat/completions'; // 默认路径
  }
};

// 延迟函数，用于创建更平滑的打字效果
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

export interface Message {
  role: 'user' | 'assistant' | 'system';
  content: string;
}

export interface ChatResponse {
  id: string;
  object: string;
  created: number;
  model: string;
  choices: {
    delta: {
      content?: string;
      role?: string;
    };
    index: number;
    finish_reason: string | null;
  }[];
}

export const useChat = () => {
  const isLoading = ref(false);
  const error = ref<string | null>(null);
  
  // 处理接收到的文本块，将其分解成单个字符并逐个输出
  const processTextChunk = async (text: string, onChunk: (text: string) => void) => {
    // 如果是单个字符，直接返回
    if (text.length <= 1) {
      onChunk(text);
      return;
    }
    
    // 将文本分解成字符数组
    const chars = Array.from(text);
    
    // 逐个字符输出，添加小延迟使显示更加平滑
    for (const char of chars) {
      onChunk(char);
      
      // 根据字符类型确定延迟时间
      let charDelay = 15; // 基础延迟
      
      // 标点符号增加延迟
      if (['.', '!', '?', '。', '！', '？', '；', ';', ':', '：', ',', '，'].includes(char)) {
        charDelay = 45; // 标点符号停顿更长
      } else if (char === ' ' || char === '\n') {
        charDelay = 10; // 空格和换行延迟稍短
      }
      
      await delay(charDelay);
    }
  };
  
  const streamChat = async (messages: Message[], onChunk: (text: string) => void, onComplete: () => void) => {
    isLoading.value = true;
    error.value = null;
    
    try {
      // 使用代理URL而不是直接使用BASE_URL
      const proxyUrl = getProxyUrl();
      
      const response = await fetch(proxyUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
          model: MODEL,
          messages,
          stream: true
        })
      });
      
      if (!response.ok) {
        throw new Error(`API 请求失败: ${response.status}`);
      }
      
      if (!response.body) {
        throw new Error('响应中没有数据');
      }
      
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      
      let done = false;
      let buffer = '';
      
      // 实时处理流式响应
      while (!done) {
        const { value, done: readerDone } = await reader.read();
        done = readerDone;
        
        if (value) {
          const chunk = decoder.decode(value, { stream: true });
          buffer += chunk;
          
          // 处理多行数据
          let lines = buffer.split('\n');
          buffer = lines.pop() || '';
          
          for (const line of lines) {
            if (line.trim() === '') continue;
            if (line.trim() === 'data: [DONE]') continue;
            
            try {
              // 去除 "data: " 前缀并解析 JSON
              const jsonData = line.replace(/^data: /, '').trim();
              const data: ChatResponse = JSON.parse(jsonData);
              
              if (data.choices[0]?.delta?.content) {
                // 处理文本块，将其分解为单个字符并逐个显示
                await processTextChunk(data.choices[0].delta.content, onChunk);
              }
            } catch (e) {
              console.error('解析数据时出错:', e, line);
            }
          }
        }
      }
      
      onComplete();
    } catch (e) {
      const errorMessage = e instanceof Error ? e.message : '未知错误';
      error.value = errorMessage;
      console.error('聊天请求错误:', errorMessage);
    } finally {
      isLoading.value = false;
    }
  };
  
  return {
    streamChat,
    isLoading,
    error
  };
};
